package com.peng.rpc.util;

import com.peng.rpc.entity.RpcRequest;
import com.peng.rpc.entity.RpcResponse;
import com.peng.rpc.enumeration.ResponseCode;
import com.peng.rpc.enumeration.RpcError;
import com.peng.rpc.exception.RpcException;
import lombok.extern.slf4j.Slf4j;

import java.util.Objects;

/**
 * @author Wonderson
 * @email wpp.ds@foxmail.com
 * @date 2022-03-03 21:46
 */
@Slf4j
public class ResponseChecker {

    private static final String INTERFACE_NAME = "InterfaceName: ";

    public static void check(RpcRequest rpcRequest, RpcResponse rpcResponse) {
        if (Objects.isNull(rpcResponse)) {
            log.error("调用服务失败,serviceName:{}", rpcRequest.getInterfaceName());
            throw new RpcException(RpcError.SERVICE_INVOCATION_FAILURE, INTERFACE_NAME + ":" + rpcRequest.getInterfaceName());
        }

        if (!rpcRequest.getRequestId().equals(rpcResponse.getRequestId())) {
            throw new RpcException(RpcError.REQUEST_ID_NOT_MATCH, INTERFACE_NAME + ":" + rpcRequest.getInterfaceName());
        }

        if (rpcResponse.getResponseCode() != ResponseCode.SUCCESS.getCode()) {
            log.error("调用服务失败,serviceName:{},RpcResponse:{}", rpcRequest.getInterfaceName(), rpcResponse);
            throw new RpcException(RpcError.SERVICE_INVOCATION_FAILURE, INTERFACE_NAME + ":" + rpcRequest.getInterfaceName());
        }
    }
}
